package org.amphiprion.rfreplayanalyser.ui;

import javax.swing.JSlider;

public class ReplayTimeThread extends Thread {
	private volatile boolean needToPause;
	private volatile boolean needExit;
	private JSlider slider;
	public float speed = 1;
	private long lastRealTime;

	public ReplayTimeThread(JSlider slider) {
		setName("ReplayTimeThread");
		this.slider = slider;
	}

	@Override
	public void run() {
		needToPause = true;
		lastRealTime = System.currentTimeMillis();
		// System.out.println("start");
		while (!needExit) {
			try {
				Thread.sleep(30);
				if (needToPause) {
					pausePoint();
				}
				long elapsed = (int) ((System.currentTimeMillis() - lastRealTime) * speed);
				if (speed != 0) {
					slider.setValue((int) (slider.getValue() + elapsed));
				}
				lastRealTime = System.currentTimeMillis();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// System.out.println("stop");

	}

	public synchronized void pausePoint() {
		while (needToPause) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public synchronized void pause() {
		needToPause = true;
	}

	public synchronized void unpause() {
		if (needToPause) {
			lastRealTime = System.currentTimeMillis();
			needToPause = false;
			this.notifyAll();
		}
	}

	public synchronized void quit() {
		needExit = true;
		if (needToPause) {
			unpause();
		}
	}
}
